TK3 SIMULATOR AND PIC18F UPGRADE 7301 words 27DEC04

John Becker

[intro]Detailing the latest additions to EPE's PIC assembly and programming
toolkit.

THIS short article describes the latest facilities that have been added to
the author's [i]EPE PIC Toolkit TK3[r] PIC assembly and programming
software, now released as version V3.00.

The first addition is a quite sophisticated Mini Simulator through which
your own software routines can be put through initial testing procedures,
allowing potential bugs to be eliminated prior to downloading the code to a
PIC.

The second enhancement is the expansion of the assembly, programming and
disassembly routines to allow members of the recently introduced
PIC18Fxx2/xx8 family to be handled. These devices have more commands and
abilities than the more familiar PIC16Fxx devices, but have significantly
different assembly and programming requirements.

[xh]Mini Simulator

For some years the author has resisted the temptation to write PC software
which would allow a PIC's assembly code (ASM) to be tested in advance of
sending its associated HEX file to a PIC. The main reason for resisting is
that it was felt the writing of such a program would be highly
time-consuming and difficult.

However, Richard Hinckley, in his [i]PIC Breakpoint[r] article of xxx,
illustrated a technique for displaying on a PC screen the code values held
by PIC registers in a semi-realtime situation. Impressed by the usefulness
of this display, the author began wondering if a similar display might be
used to show register value changes while the PC did the actual processing
of the assembly code, rather than the PIC itself.

One hot day last UK summer, when it was more comfortable to stay indoors, a
brief test program was written in which register values were displayed on
screen in boxes similarly positioned as in Richard's [i]Breakpoint[r]. The
results were encouraging, and more readily accomplished than had been
anticipated.

So the tests continued, maturing into more specific functions, all related
to the full suite of 33 codes as recognised by a PIC16F device, such as the
F84, F628 and F877 etc, which TK3 has long been able to handle.

Eventually, the Simulator reached the point at which many useful
pre-programming functions had been added, in addition to the basic
step-by-step simulation. At that point, by chance [i]EPE[r] reader John
Waller, with whom the author regularly email chats about PICs and other
matters, expressed an interest in trying the Simulator with the software he
was writing. This was for the model train semaphore signals controller he
was developing.

There ensued a lively exchange of emailed ideas and Simulator code
developments, effectively resulting in the software described below.

[xh]Preparing for Simulation

To use Simulation mode, the assembly (ASM) code that you have written is
first assembled in the normal way, generating the usual HEX code. In doing
so, though, it also generates another file having the same base name, but
suffixed with .SIM. To this file are written the ASM commands, along with
the HEX code values, and their command count addresses. These values are
stored in the file in strict order of the same addresses as the PIC would
see them. Also stored to this file are the equated register names and their
address numbers.

Consequently, during simulation, all the branches, GOTOs and CALLS are to
the same addresses as the PIC would see them, and the registers have the
same values written to and read from them as when the PIC is running in
real life. The Simulator thus allows a full check to be made of what is
occurring as each command is processed.

When assembly has been completed, the actual HEX file is ignored at this
time. Instead, the Mini Sim button on TK3's main screen is clicked, and the
Simulator function is launched. This loads the SIM file, displaying the
commands in a List Box, and storing the HEX codes to a memory array.

Simultaneously, any register values and their equated names actively used
in the ASM file are allocated in numerical register order to the main Sim
screen area. Here there are 128 zones arranged in columns, numerically
ordered from top to bottom, left to right.

The register names are shown to the left of each column, and their current
values to their right. Any zone which does not have an allocated register
name is allocated a default name, prefixed as GPReg (general purpose
register), followed by its address number in hexadecimal (e.g. GPReg4B). If
the PIC in question has registers which are unavailable (e.g. register
address 7 is unused in the PIC16F84), the name is shown as n/a (not
available). Until register values have actually been set while running the
simulation, their value boxes remain empty except for a hyphen symbol.

There can be more than 128 registers involved for any PIC, and any whose
addresses are greater than 127 (remember that zero is an address in this
context) are stored "behind" the screen, in numerical order in temporary
storage arrays.

Any group of 128 registers and their values can be called up for display
instead of the first 128 registers block by means of the Bank selection
buttons at the top left of the screen. The buttons behave "exclusively" so
that only one Bank can displayed at a time. The selected Banks correspond
to the allocated Banks for the PIC16Fxx family. Not all of these PICs have
four Banks available, in which case, only those available can be selected.
The PIC16F84, for instance, has only two Banks, whereas the PIC16F877 has
four. Conversely, the 18F family have more than four banks (16 for the
18Fxx2/xx8 devices), and they can be selected in groups via another button
when in 18F mode.

Note that when assembling an ASM file, unless it has the PIC type embedded
in it (near the top of its code, in the form: LIST = P16F84) you [i]must[r]
set the PIC type correctly via the usual [i]TK3[r] main screen option.

[xh]Running a Simulation

Two buttons, Run Simul and Step Simul, on the Sim screen allow the program
to be cycled through each command in order, and its associated HEX command
value processed accordingly. The numerical results of each command are
displayed in the dedicated register boxes as appropriate.

Normally the register boxes are uncoloured, but become coloured (light
blue) when they are accessed. This aids good visibility. Additionally, the
captions in each box show in red while they are currently accessed,
reverting to black when the next register is selected.

In Run mode, the sequence starts at the first command listed (or as
selected), and the program automatically processes each command in order as
it is encountered, amending values and branching to other segments of the
code as instructed, as would a real PIC.

The main difference to a PIC is that you can stop the simulation at any
point and examine the current status of the registers. To do this directly
with a PIC, Richard's [i]PIC Breakpoint[r] program is needed.

The processing speed is also different. When Run mode is started, the
program steps through the commands at a rate determined by the Sim
program's internal timer interrupt.

When clicked to start running, the Run button's caption changes to Stop and
its green colour changes to red. Click the button to stop automatic
running.

Run mode is of particular benefit when it is the results of processing one
or more code routines that are more significant than the immediate results
of each command, as provided by Step Mode.

In Step mode, the process is identical to that in Run mode, except that
each click of the Step button simply steps the simulation sequence on by
one command, then waiting for the next click before stepping on again. This
allows the results of each command to be examined at leisure. Note that a
particular line in the program is executed as soon as the simulation steps
into it. For example, if you are simulating a timing loop, and you want to
check a particular action occurs correctly when TMR2H reaches a particular
value, then that value must be set into TMR2H [i]before[r] stepping into
the line where TMR2H is read.

[xh]Selective Simulation

In either Run or Step mode, the starting point for the simulation can be
set at any command. Alongside the Listed commands are small tick-boxes. To
select any command as the start point, left-click on the selected command's
box, then right-click at the same point. This action stores the starting
point to memory, and is also confirmed in the small green box below the
List screen. Clicking Run or Step now causes the simulation to start at
that point.

Run mode can be terminated at any point beyond the start point (or even
before it if commands there are branched to from a command further down the
list). To select a stop (break) point, left-click on the required box, but
do not right-click it.

When Run commences at the start point, the sequence of commands is
processed until the break point is reached. Run mode then terminates and
reverts to Step mode.

To repeat the simulation sequence from the designated start point, click
the RPT button.

The start point can be changed in the same way as it was set. You may have
several break points set simultaneously, each set by clicking on its tick
box. When Run mode is again clicked following a break, the sequence then
continues until the next break is reached, and so on. The break points only
have significance for Run mode - in step mode, each command is processed as
an individual action.

Break points can be deleted by clicking on the ticked box. The tick changes
state on an alternating cycle. It is important to note that it is the
[i]box[r] which must be clicked, not the line itself. The latter [i]may[r]
appear to work sometimes, but the tick behaviour can be erratic (a VB6
problem). Do not double-click a box.

All start and break points can be cancelled by clicking on the Clear Breaks
button.

Neither the RPT nor the Clear Breaks button affect the register values. To
clear the registers back to zero (null) values, click the Reset button.
This also resets the register box colours to neutral grey. Note that break
points are unaffected by Reset.

By default, the register values are displayed in decimal. They can, though,
be displayed in any radix, decimal, hexadecimal or binary. Three buttons
below the Bank buttons select the radix mode.

[xh]Changing Register Values

Any displayed register can have its value changed manually when in Step
mode. To do so, click on the register, at which a selection of other boxes
appears at the top of the screen. The screen then displays the register
name, its value in decimal in a text box, and as a binary value in eight
tick boxes. Clicking any tick box changes its logic state and the resulting
new byte is shown in the text box. Alternatively, you may change the text
box value by keying in a new value, from 0 to 255. Values must be in
decimal.

Clicking the register name to the left of the text box (or pressing Enter)
causes the new value to be stored back to the selected register. At this
point the Change option closes and is removed from screen. Clicking Run or
Step also performs the same action.

[xh]Flag Bits

In addition to register values being displayed, so too are the Status
register flag bits in their own boxes, below the List screen. The flags
displayed are for the C, DC, Z bits (plus IRP, RP1, RP0 for non-18F
devices, plus N and OV for 18F), with their status shown in binary (1 or
0).

These bits can be changed manually by clicking on them, causing them to
alternate between states. The displayed value of these bits is responded to
when the simulation is running.

[xh]W Register

The W register value has been allocated its own box, to the left of the
Status flag bits. This is constantly updated while the simulation is in
progress. It too may be changed manually, in the same way as for the other
registers.

[xh]Tooltip Texts

Visual Basic 6 (VB6), in which this program has been written, allows
"Tooltip Text Boxes" to be allocated. These are normally allocated with
text at the time that the program is written. However, they can be given
texts while the program is running and advantage of this has been taken. If
you hover the mouse cursor over any register value box, that value will be
displayed in a yellow box in decimal, hex and binary, irrespective of the
radix mode selected.

Hovering the mouse over any register name will cause that register's
address to be displayed in HEX. Hovering it over the flag boxes causes the
full value within the Status register to be displayed in all three radix
forms. Hovering it over the W box shows that value in all three radix
modes.

Many other on-screen function buttons have Tooltip Texts, displaying a
brief description of what that button does.

Furthermore, hovering the mouse over the List screen commands causes the
full text of that line to be shown (within the length limits imposed by
VB6); useful on the List screen when long command lines are truncated.

[xh]Word Find

A Find command button has been provided below the List screen. Above the
button is a text box. Key in any word (or phrase) which might occur in the
commands listed, click Find (or press Enter) and the routine will find it
for you if it exists, highlighting the line in which it occurs. If it is
not found, a message display will tell you so. Further clicking of Find
will display further occurrences of the word until the end of the list is
reached. Re-clicking Find will then start the search from the top.

[xh]PIC Stack

PICs have a Stack register which keeps track of return addresses when CALL
commands are actioned. In the PIC16F family, this register cannot be read
from or written to directly. It has a limit of eight addresses and can be
inadvertently overwritten if this count is exceeded in a complex program
having nested sub-calls. Such overwriting invariably causes a major program
crash.

The Simulator keeps track of the Stack status and displays it in a separate
list box a little below the command list box. The values shown are the
addresses, in reverse calling order (last in, first out) and in decimal, to
which the program jumps when a RETURN or RETLW command is performed. The
values are one greater than the address from which the CALL was made.

When a return is made, the return address is "popped" from the stack, and
return addresses below it are rippled back up the stack. This is a
particularly useful facility as complex programs can generate many "nested"
calls and unwary program writers can cause the stack to overflow, with the
eighth address being lost, and consequent mayhem in the program!

[xh]Ports

The Ports are different to other registers in that they are effectively two
registers, one for data output to the world, the other for input from it,
as determined by the setting of their TRIS (data direction) registers.

The basic function of a PIC16F Port bit is illustrated in the schematic
drawing shown when the Ports Info button is clicked. Microchip state that:
"Reading a port register reads the status of the pin, whereas writing to it
will write to the port latch. All write operations are read-modify-write
operations, so a write to a port implies that the port pins are first read,
then this value is modified and written to the port data latch."

At the bottom of the screen, the PORT IN buttons in the first line
represent the data logic levels available to be input when the relevant
TRIS bit is set for input, alternating between High and Low logic when
clicked, black or white respectively. In some respects they can be regarded
as external switches connected to the pins. The blue boxes below them show
the equivalent numerical value of the input logic bits.

The small PORT OUT boxes represent the logic levels available to be output
to the world from the data latch. The value is that determined by reads
from the input pins and that set by data writes to a port (re-read
Microchip's statement if this is not immediately clear). The data actually
output is modified by whether relevant TRIS pins are set for input or
output. The blue PORT OUT boxes show the equivalent numerical value of the
data latch contents. On the main body of the screen, the register boxes for
the Ports show the same data latch value.

The second-from-bottom line of boxes shows the TRIS bits, red for input
mode, and blue for output mode.

With some PICs, pins can be selected for analogue or digital mode, as set
by CMCON in an F628 for instance. For this work, of course, the PIC type
and configuration value must be included in the ASM file in the
conventional manner (see discussion of 18F demo program later). When a
simulation for such PICs is being run, an additional line of boxes at the
bottom shows the analogue/digital status.

[xh]Missing Labels

Any Labels written into an ASM file are only repeated in the SIM file if
they have a command associated with them. The SIM file is created at the
same time as the HEX file and records only those statements for which a
code value and address are given. Any line without such is ignored.

The SIM screen list box is arranged in strict numerical order of addresses
as the PIC would see them and any additional lines would throw the program
count correctness and Calls/Gotos/Returns etc would not be implemented
properly. The only way round this is for you to add NOP at any label
without a command where the label needs to be shown in the SIM list.

[xh]Command Timings

Each command actioned takes one or two PIC cycles (as listed in its data
sheet), which occur at one quarter of the PIC's clock (e.g. crystal) rate.
The simulator keeps track of the command cycles and displays them at the
bottom left of the screen. By default they are in relation to a 4MHz
crystal rate (1 cycle = 1 microsecond).

You may change this rate via the Combo box below the cycle counter display.
The choices are 32768Hz, 3.2768MHz, 4MHz, 10MHz, 20MHz. No provision has
been made to add to the choices. Click on the box's arrow and select from
the list displayed. The choice is not stored for future recall when next
the program is run, reverting to 4MHz.

[xh]Hide Unused

Normally, the screen displays all registers associated with a PIC Bank. You
may "hide" unused registers by clicking on the Hide Unused tick box at the
bottom left. Re-click to re-display them all.

[xh]Edit and Assembly Buttons

The Edit button calls up the same Edit facility as accessed via TK3's main
screen, allowing the ASM code to be modified. Exiting the Edit function
returns you to the Sim screen, where an ASM button is now shown. Click it
to start code assembly in the normal way.

On completion of the assembly, that sub-screen offers the same options as
usual, plus the option to re-enter the Simulation screen. (It has proved
impossible to offer an automatic assembly entry from the Simulation screen
following exit from Edit - as is provided via the main screen's function
using the Enter key.)

The Edit and Assembly buttons are hidden during automatic simulation (Run)
mode.

[xh]Trace Button

The Trace tick box allows you to make a record of the commands actioned
while in automatic Run mode. On starting the run, a file is opened
(TK3Trace.txt) and each command actioned has its code line output to the
text file, along with its address value. On stopping auto-run, the file is
closed and can then be examined via the Show Trace button.

The recording always starts from the current line selected. The recording
facility is not available when single-stepping a program, or when the Trace
box is unticked. The record is always overwritten when a new run is
started.

[xh]Main Screen Simul Button

The simulation facility can be inhibited via the main screen. To the left
of the Mini Sim button is a tick box. Click the box to hide the tick, this
also hides the Mini Sim button. Re-click the tick box to reactivate the
option.

The benefit of turning off the Simul option is that it prevents .SIM files
being created during the assembly process. If you are changing the ASM file
name for each new version of that code (as is recommended, by using a
suffix number for example), your disk drive could become "well-populated"
by SIM files that you do not need. This inhibit option prevents SIM files
from being created when you do not want them.

[xh]Simulating HEX Files

If you only have a HEX file for a particular program and wish to simulate
it, first convert the HEX file to an ASM file via TK3's Hex Disassembly
option. Then assemble the resulting ASM file to create a the required SIM
file). Remember that you must set the PIC Type for the PIC being
disassembled.

[xh]SIM FILE EXAMINATION

The Sim file may be examined via the main screen or sim screen View Sim
buttons. This is for information only and has no practical purpose.

[xh]Limitations

This mini simulator does not attempt to match the facilities of more
sophisticated commercial simulators. It basically shows the behaviour of
the commands in a program and the affects that they have upon the registers
accessed. The following are not supported:

Interrupts
Access to Data Eeprom
PortB pullups
Sleep
Analogue inputs and other special I/O functions (e.g. RS232)
Timers, including WatchDog, with the exception that a mock creation of a
TMR0 rollover is generated in response to the simulator's own internal
timer

The program has a limit of 8000 PIC commands, 512 registers (4 Banks) for
non-18F devices and 4094 registers (16 Banks) for 18Fs.

All code changes must be made through the normal Edit/Assemble functions,
they cannot be changed from within the simulator.

Whilst the simulator was originally designed for the PIC16F family, most
aspects should also function with the 12F and 18F families. However, with
the 18F family facilities, there are several other limitations, some known,
others yet undiscovered.

Of the known 18F limitations (in addition to the 16F ones), table read and
write commands (TBLRD, TBLWT) cannot (as yet) be processed correctly. As a
final comment on the simulator, it was originally written with the
expectation that it would be used to check short code routines before
implementing them into a larger program. Although it has been proved that
some longer programs can be simulated, it is not guaranteed that all can
be. If you wish to make helpful suggestions about improving this simulator,
contact the author as stated later.

[xh]PIC18Fxx Family Facilities

Following determined persuasion by a number of readers, in the summer of
2004, the author embarked upon the task of upgrading TK3 to handle the
fairly recently introduced PIC18Fxx family. These have a host of extra
facilities not offered by the more familiar 16F8x, 16F87x and 16F62x
families. Malcolm Wiles will be formally introducing the family to you next
month.

In terms of TK3, the upgrade requirements were to add recognition of the
extra commands, and to amend the programming algorithm to 16-bit instead of
14-bit. At first sight this appeared to be a straight-forward though
lengthy upgrade.

Restructuring TK3 to handle 18F commands as well as the existing 16F and
12F commands proceeded fairly readily, although it was soon recognised that
splitting the Assembly routine into two separate functions would be
preferable, avoiding many "IF 18F THEN ... ELSE ...END IF" statements.

By September, that split with all its implications and accessory routine
procedure amendments had been finalised. Time to amend the Programming to
send 16-bit as well as 14-bit hex values. Fortunately, it seemed,
Microchip's datasheet had provided examples of the programming structures
needed to send and read back 16-bit words to/from 18F devices. These were
followed and tested.

Disaster - they did not work, or if they did they were unreliable in their
repeatability. Browsing Microchip's data in all directions did not reveal
solutions, but it did reveal documentation anomalies and ambiguities.
Microchip's technical department were of no help, simply sending an
automated reply to a querying email telling the author to browse their web
site for information; which had already been done anyway, to no avail.

By mid-October, the author recognised that this was a battle he might not
win (not often that happens!). However, Malcolm Wiles, professional
programmer and knowledgeable in the C language and its derivatives,
provided the author with his C++ routines which [i]did[r] successfully
program 18Fs.

Analysing Malc's commands clarified the Microchip ambiguities (although
Malc too had earlier had trouble interpreting their published data in
several areas). It also revealed a previously unknown problem with VB6, the
software in which TK3 is written. Any value written in hexadecimal form
representing a two-byte decimal value of 32K or greater is translated by
VB6 to a [i]negative[r] value comprising three bytes.

Many of the formatting commands required in the PIC programming routines
are expressed in Microchip's documentation as hex values from 0000 to in
excess of 7FFF (32767 decimal), well beyond VB6's "negative" boundary.
Consequently, TK3's software, which sends decimal values in serial bit
streams to the PIC, was sending the wrong format commands. Malc's software
helped reveal this problem (C++ does not suffer the same value problem), as
well as clarifying Microchip's requirements.

TK3 18F programming success was achieved in mid November! This included
sending programming commands, configuration values and EEPROM data, and
reading back data from all locations.

Following extensive bench and field testing, TK3 with 18F facilities is now
released to the world! However, the current version should be treated as a
"beta" version still under field trials. If you spot anything which is not
as it should be, please tell the author via [i]EPE[r].

This request particular applies to the 18F Simulation which has had less
opportunity to be tested "for real".

[xh]PIC18F Differences

As Malcolm will explain, there are several differences between 18F and 16F
devices in the way in which code must be written.

Also be aware that MPASM (as at V3.50) no longer recognises the following
shorthand commands when assembly 18F code:

CLRC, CLRDC, CLRZ, SETC, SETDC, SETZ, SKPC, SKPDC, SKPZ, SKPNC, SKPNDC,
SKPNZ

If you wish to use these valuable commands with MPASM, they must be defined
at the head of your program. TK3 continues to recognise them for all PIC
types.

[xh]TK3 MPASM Link

Since early versions of TK3, an on-screen link to Microchip's MPASM
assembler has been provided for those who have MPASM installed. This has
been slightly upgraded in that TK3 and MPASM can now exchange file names
via two click-buttons. Using these buttons, any file name selected through
TK3 can be placed in MPASM's assembly program (via its .INI file, line 2),
and vice versa.

Should you ever find that TK3's assembler cannot perform a less common
function which is available through MPASM, don't hesitate to assemble your
ASM code through MPASM. The hex file created through MPASM is totally
compatible with TK3 and can be programmed into the PIC through TK3.

Similarly, any hex file generated by TK3 is believed to be totally
compatible with any programmer designed for use with MPASM-type files. This
is not necessarily true of ASM files created through TK3. TK3 recognises a
number of command structures (as used with the TASM dialect) which MPASM
does not. Such differences are explained in the Notes files readable
through TK3. To translate an ASM file having these different command
structures to suit MPASM's requirements, use TK3's Conversion facility.

[xh]Disassembly Functions

TK3's Disassembly functions have also been enhanced with V3.00. These now
allow a greater variety of methods through which PIC contents and HEX files
can be examined and translated to "English".

[xh]Example Program

The program in Listing 1 shows examples of some programming routines which
you should find useful. They illustrate how an alphanumeric l.c.d. can be
controlled by a PIC18F, and how this PIC's data eeprom can be written to
and read from. There are some other aspects which are also worth
highlighting, including the use of FSR and INDF.

The demo is simply aimed at getting you started with 18F. The author finds
the use of an LCD is vital when debugging a program (irrespective of
simulations) and so seems an essential first facility you might also need
when writing for 18F. Similarly regarding eeprom use, which is a facility
the author often uses (partly as a debugging aid), so again seems an
elementary tool to which you should have immediate access.

[xh]List P Directive

Some of you may not be familiar with the List P directive as in Listing 1
line 4, [bo]List P = PIC18F252 R=DEC[r]. This instructs the assembly
program that the code which it is about to assemble is for a PIC18F252. Any
PIC program can have a similar statement made at this point, detailing the
intended PIC type. The assembler, whether TK3 or MPASM etc, will then know
which procedures it is to follow in order to correctly assemble the program
for that PIC.

The directive [bo]R=DEC[r] simply tells the assembler that any value
encountered which does not have a prefix of, say, H', B', $, %, etc, is to
be taken as a decimal value. It is worth noting that the author has never
needed a radix other than decimal, and the statement can just be copied as
shown for your own programs (or even omitted).

[xh]Include Directive

Line 5 has the statement [bo]include P18F252.inc[r]. This tells the
assembler it is to use the register equates values given in the Microchip
"include" file for the same PIC type. This saves you having to key in your
own list of the required special function registers (SFRs) and their
allocated addresses (e.g. PORTB EQU xx, etc).

The "include" file name is prefixed by "P", followed by the PIC type. MPASM
"include" ([bo].INC[r]) files for the entire PIC range can be downloaded
from their website. They are also included with Microchip software such as
MPLAB and MPASM. A selection of those for the PICs which TK3 recognises are
included with TK3's software.

[xh]Configuration

Next follow 14 configuration statements. The 18F family have more complex
configuration arrangements than, for example, the 16F family with which you
will be familiar. TK3 has now been given a dedicated config screen through
which these values are established (Photo). The screen has its own Notes
through which you can read about the screen but, basically, you click on
the required functions you wish to set or reset, either through their
allocated boxes, or via the List sub-screen and its tick boxes.

Having made your selection, click on the Copy Output button. This copies
all 14 config values to the Windows clipboard. You then open the ASM file
for the program being developed and paste the values into it, which are
correctly formatted in the style shown in Listing 1.

When the program is assembled, the config values are placed into the HEX
file and automatically programmed into the PIC when the HEX code is sent to
it. The config screen also allows you to readback config values from the
PIC, and to send the values directly to the PIC, although there is rarely
any need for the latter to be done separately. It is stressed that you
[i]must[r] have the 18F family datasheet in order to fully understand the
functions of the config options.

[xh]Erasure and Code Protection

It is worth commenting that the program and data eeprom contents of a
PIC18F are automatically erased when the PIC is reprogrammed.
Simultaneously, the config values are reset to their defaults, and all code
protection values are cleared. Config can be written to or read from
regardless of any code protection which may be on.

[xh]Access and Banked

As Malcolm explains next month, PIC18F devices have Access and Banked
addresses. Their function is somewhat analogous to using the BANK0/BANK1
(PAGE0/PAGE1) directives of the 16F family, but more subtle. Any command
which causes a PIC register to be written to or read from should indicate
whether that register is in the Access or Banked bank. This is done through
TK3 by the use of "A" or "B" as part of the command (MPASM also allows the
use of the suffix ACCESS or BANKED, but TK3 does not).

Normally you will only work with registers in the Access bank and so letter
"A" will be the suffix, as is shown throughout Listing 1. If you omit to
add the suffix, TK3 will remind you, but still assemble as though "A" had
been used.

A full list of the 18F commands recognised by TK3 can be read via the Show
PIC Codes button at bottom right of the main screen. The codes also show
which suffixes are needed with each command, e.g. ADDWF requires f,d,a, in
other words, it needs the file name, destination F or W, and Access bit (A
or B).

[xh]CBLOCK Directive

Recognition of the CBLOCK/ENDC directives is a fairly recent addition to
TK3. This is an MPASM structure which allows you to allocate your own named
registers without giving them specific EQU XX values. The register names
you want are simply listed following the CBLOCK statement. The list is
terminated by the ENDC directive.

During assembly, each resister is given a consecutive address starting from
the value following the CBLOCK statement. In the case of Listing 1, there
is no value given, and the value is taken as zero (18F registers can start
from 0, unlike 16F registers which typically start at H'0C' or H'20'
depending on PIC type). For non-18F PICs, TK3 allocates the relevant number
even if it is omitted - unlike MPASM, which always treats an unspecified
CBLOCK value as 0.

[xh]ORG and TRISx

As with other PIC families, the assembler/programmer must be told the PIC
memory location (address) from which it must start to place the commands.
With 18Fs, the first available working location is after the Interrupt
location at H'18'. See the datasheet for details of the locations up to
H'18'. [i]Do not[r] specify location 5 as the starting address for 18Fs,
which is what you would probably do with 16F devices.

Unlike 16Fs, 18Fs do not require the use of BANK1/BANK0 directives when
setting the TRISx values. They are simply set as shown in Listing 1 at the
label START.

[xh]Timer 0

Timer 0 with the 18Fs is set similarly to the same timer in 16Fs, except
that register T0CON is the one used to set the timer's precount ratio
(instead of xxx). The value shown in Listing 1 (B'11000110') sets the timer
precount to 1:64.

[xh]PCL Counter and Tables

Accessing Tables though the PCL program counter (as required for 16F
devices) is not needed with the 18F family. Instead, tabled values are read
through the setting of table pointers and versatile TBLRD commands, and
there is no limit to the length of tables. Examples of 18F table access are
shown in Listing 1, where the tables are at labels TABLCD, MESSAG and
MESSAG2. Malcolm will explain table use more fully next month. Apart from
this change to any table use, alphanumeric LCDs are controlled in same way
as for other PICs.

It is still possible to use PCL for tables, but a crucial point to note is
that PCL behaves differently to PCL in the 16F. This requires a change to
any loop which calls PCL-governed tables, in that the loop counter must be
[i]doubly[r] incremented following each call to the table. If it were to be
only singly incremented (in the more familiar manner) each line in the
table would be accessed twice.

Double incrementing for PCL accessed tables is essential in order to access
each line consecutively and incrementally. The loop count thus has to be
twice the length you might normally expect, i.e. for an 8-line table
access, a loop of 16 counts must be set. The knock-on effect is that tables
are limited to 128 lines instead of the normal 256.

In Listing 1, the LCD is initialised to 2-line 4-bit mode, then a tabled
8-character message (MESSAG) is sent to LCD screen line 1. The routine is
written to suit the standard LCD pinout order on TK3's p.c.b.

[xh]Data EEPROM Writing

Next, for the sake of demonstration, values in the third table (MESSAG2)
are sent for storage in the PIC's data eeprom. This is a subject which gave
the author much grief many years back when he began investigating PIC16C
devices, Microchip's datasheet then being erroneous. The 18F datasheet in
this respect is not totally explicit, and a certain amount of
experimentation had to be done before writing to the data eeprom was
successful. Reading from it was straightforward. But with both routines,
knowledge gained from other PICs was invaluable for getting the 18F to
function correctly.

When writing to the eeprom, the value to be written is first placed in a
temporary register (STORE, or other name of your choosing), the address at
which the value is to be stored in the eeprom is then loaded into W, and
the SETPRM routine called. A somewhat "black-art" set of commands follows,
which should be copied parrot-fashion into your own programs. All you need
to concern yourself with is the loading of STORE and W.

[xh]Data EEPROM Reading

When reading the eeprom, simply load W with the eeprom address from which
to read the data, then call GETPRM. The routine is exited with W holding
the value from the specified location. Again, copy the routine as it is
into your own program.

In Listing 1, having placed eight extra values into the eeprom (at its
locations 8 to 15), the first eight values (at locations 0 to 7 - set there
as discussed next) are read back and displayed at the right of screen line
1. The new eeprom values are read and displayed on screen line 2.

Note the way in which the screen line is selected (call LCD21). A perpetual
holding loop is then entered (NOMORE) and no further actions occur. It is
suggested that you experiment with the table messages (but don't amend
TABLCD), and those DE-prefixed values at the end of Listing 1.

[xh]Embedded Data EEPROM Values

At the end of Listing 1, are the values which the assembler loads into the
HEX file for subsequent automatic placing into the PIC's data eeprom, at
locations 0 to 7 in this case. You will see the ORG value of H'F00000' - a
very large value for a PIC you might think. Fortunately, it is not an
address value as such, but merely a value which the assembler knows means
that subsequent values are for the eeprom.

Be aware that MPASM treats pairs of values in a DE line as a single value
compacted into one word (two bytes), and individual DE values also as two
bytes but with the second having a value of zero. TK3 treats all data
values as two bytes with the second as zero, and when reading the eeprom
this zero value is "unseen".

[xh]FSR and INDF

The use of indirect addressing through FSR and INDF is also different with
18F devices. Practical examples are shown near the end of Listing 1. For an
understanding of the logic behind the commands, it essential to read the
18F datasheet, noting that there are several indirect addressing registers
in addition (but similar) to those in the examples.

[xh]Obtaining TK3 V3.00

The software for TK3 V3.00, which includes the Simulation, 18F facilities
and Listing 1 (TK3PIC18FDEMO2.ASM), is available via the [i]EPE[r] web site
at [bo]www.epemag.co.uk[r]. Click the usual Downloads button on the home
page, and then access the PIC Microcontrollers path and select folder
Toolkit TK3. Download all files within that folder into a new folder on
your PC, under whatever name you choose. It is suggested that you do not
delete the earlier TK3 folder, just rename it.

Note that what used to be sub-folders named Disk 1 and Disk 3 have now been
combined into one folder named Disk1-3. This holds the standalone
([bo]Toolkit3.exe[r]) file, all the associated text files etc, and the TK3
VB6 source code. The original Disk 3 held only the source code and is no
longer required on its own (or available).

If you have not downloaded TK3 before and do not have VB6 installed on your
PC, you [i]must[r] use the files in folder Disk 2. These are Microsoft
"runtime" files required for use with the standalone [bo]Toolkit3.exe[r].

Where files are zipped, unzip them all into the same folder holding the
rest of TK3's files. Winzip is the suggested unzip facility, and should be
part of any PC's software. If you do not have it installed, it may be
download free from [bo]www.winzip xxxx[r].

Unless you are already familiar with PIC18F devices, wait until you've read
Malc's introduction to them next month before putting them to use. There
are certain other critical differences which you need to appreciate. You
should also obtain the Microchip datasheet (DS39564) for the 18Fxx2/xx8
devices, from [bo]www.microchip.com[r]. It is over 300 pages, but is
essential to understanding the devices.

[xh]Acknowledgements

The author wishes to thank John Waller for the active field testing he did
over several weeks with the Simulator and a PIC16F62x program he was
working on, making many invaluable suggestions which were then implemented.
John's project, [i]Model Railway Signal Control[r] (or similar name), will
be published shortly.

Malcolm Wiles is also warmly thanked for his invaluable help with getting
TK3 to program 18F PICs. In places Microchip's documentation is less than
clear and Malc clarified a number of points which for some time presented
the author with seemingly insurmountable hurdles. Malc is currently
offering advice on further improvements in respect of 18F devices. Updated
TK3 software embodying Malc's suggestions will be released when
appropriate.

Malc's [i]Introduction to the PIC18F Family[r] will be published next
month, in the April '05 issue.

Several other readers, too numerous to mention individually, have also
assisted in various ways in the upgrade to TK3 V3.00. Very many thanks for
your help too!

Don't forget that TK3 now embodies Richard Hinckley's [i]PIC Breakpoint[r],
and several contributions by Andrew Jarvis to add more PIC types and
associated software tools to TK3's repertoire. And Ian Stedman has
contributed a TK3 FAQ file which is in the TK3 folder on the Downloads
site. Thanks guys!

If you wish to provide the author with feedback about TK3, you can do so
via his [i]EPE[r] email address, [bo]john.becker[at]wimborne.co.uk[r].
LAYOUT 000
:  B P           <   ?   A    \-------------+----------------+--------------------+----------@----------/---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+----                        BP           <   ?   A    ---------\----+---------------